package cn.itsource.hrm.exception.handler;

import cn.itsource.hrm.exception.GlobalException;
import cn.itsource.hrm.util.AjaxResult;
import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestControllerAdvice
@Component
public class GlobalExceptionHandler {

    @ExceptionHandler(GlobalException.class)
    public AjaxResult globalExceptionHandler(GlobalException e) {
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setCode(e.getErrorEnum().getCode()).setMessage("保存对象失败！" + e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e) {
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setCode("555").setMessage("后台出现问题，程序员正在抢修中...");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult exceptionHandler(MethodArgumentNotValidException e) {
        e.printStackTrace();
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return AjaxResult.me().setSuccess(false).setCode("500").setMessage(message);
    }
}
